package pl.soulmusic.service;

import java.io.IOException;
import java.io.Reader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import com.ibatis.common.resources.Resources;

/**
 * Utility class for using the data base. Reads the object-relational mapping
 * from the Ibator configuration files.
 * 
 * @author Mateusz Mor
 */
public class SqlMapFactory {

	private static final String CONFIG_XML = "CCM2DBConfig.xml";

	/**
	 * Logger
	 */
	
	private static final Log log = LogFactory.getLog(SqlMapFactory.class);

	/**
	 * Singleton instance
	 */
	
	private static SqlSessionFactory sqlMapper = null;

	/**
	 * Returns the singleton instance of <code>SqlSession</code>.
	 * 
	 * @return the singleton instance of this class
	 */
	public static SqlSession getInstance() {
		if (sqlMapper == null) {
			synchronized (SqlMapFactory.class) {
			    
				if (sqlMapper == null) {
					try {
					    
					    Reader reader = Resources.getResourceAsReader(CONFIG_XML);
					    sqlMapper= new SqlSessionFactoryBuilder().build(reader);
						
					}
					catch (IOException e) {
						log.fatal("IOException Creating SQLSessionFactory" + e.getMessage(), e);
					}
				}
			}
		}
		return sqlMapper.openSession();
		
	}
	/**
	 * Returns an {@link SqlMapClient} instance that is used to access the data
	 * base.
	 * 
	 * @return sqlMapClient an {@link SqlMapClient} instance that is used to
	 *         access the data base
	 */
	/*public SqlMapClient getSqlMapClient() {
		return sqlMapClient;
	}*/

}
